package com.jeesite.modules.kj.api.controller;


import com.jeesite.common.codec.DesUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.network.IpUtils;
import com.jeesite.common.shiro.authc.FormToken;
import com.jeesite.common.web.BaseController;
import com.jeesite.common.web.http.ServletUtils;
import com.jeesite.modules.kj.api.controller.base.ApiBaseController;
import com.jeesite.modules.kj.api.enumCode.UnicomResponseEnums;
import com.jeesite.modules.kj.api.vo.requestVo.login.NeedLoginListRequestVo;
import com.jeesite.modules.kj.api.vo.requestVo.member.LoginRequestVo;
import com.jeesite.modules.kj.api.vo.responseVo.ResponseBean;
import com.jeesite.modules.kj.api.vo.responseVo.login.LoginInfoResponseVo;
import com.jeesite.modules.kj.api.vo.responseVo.member.MemberInfoResponseVo;
import com.jeesite.modules.kj.user.service.UserExtendService;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import static com.jeesite.common.web.http.ServletUtils.getRequest;

//
@RestController
@RequestMapping("api/member")
@Api(value="会员APIcontroller",tags={"会员API接口"})
public class MemberController extends ApiBaseController {
    @Autowired
    UserExtendService userExtendService;
    /*
     *会员登陆接口，正式环境需要加密解密
     */
    @ApiOperation(value="会员登录",notes="会员登录")
    @PostMapping("/login")
    @ResponseBody
    public ResponseBean<LoginInfoResponseVo> login(LoginRequestVo loginRequestVo) {
        String error = executeLogin(getRequest(), getOneCodeUser(loginRequestVo.getAccount()), getPassword(loginRequestVo.getPassword()), getCaptcha(loginRequestVo.getCaptcha()));
        if(StringUtils.isBlank(error)){
            Session session = UserUtils.getSession();
            LoginInfoResponseVo loginInfoResponseVo = new LoginInfoResponseVo();
            loginInfoResponseVo.setEntity(session.getId().toString());
            loginInfoResponseVo.setMember(new MemberInfoResponseVo(UserUtils.getUser()));
            return new ResponseBean(loginInfoResponseVo);
        }else{
            return new ResponseBean(Global.FALSE, UnicomResponseEnums.NOT_MATCH);
        }

    }
    /*
     *会员登陆接口，正式环境需要加密解密
     */
    @ApiOperation(value="会员退出登录",notes="会员退出登录")
    @PostMapping("/logout")
    @ResponseBody
    public ResponseBean<String> logout() {
      Subject subject = SecurityUtils.getSubject();
      subject.logout();
      return  new ResponseBean(Global.TRUE, "退出登录成功");
    }

    /*
    会员登陆接口，正式环境需要加密解密
     */
    @ApiOperation(value="获取登陆用户信息",notes="获取登陆用户信息")
    @GetMapping("/info")
    @ResponseBody
    public ResponseBean<MemberInfoResponseVo> getInfo(NeedLoginListRequestVo needLoginListRequestVo){
        User user = UserUtils.getUser();
        return new ResponseBean(new MemberInfoResponseVo(user));
    }


    protected String executeLogin(HttpServletRequest request, User user, String password, String captcha){
        String error = "";
        if(user != null) {
            Subject subject = SecurityUtils.getSubject();
            FormToken token = new FormToken(user.getLoginCode(), password, true, getHost(request), captcha, ServletUtils.getExtParams(request));
            try {
                subject.login(token);
            } catch (UnknownAccountException e) {
                error = "用户名/密码错误";
            } catch (IncorrectCredentialsException e) {
                error = "用户名/密码错误";
            } catch (AuthenticationException e) {
                // 其他错误，比如锁定，如果想单独处理请单独catch处理
                error = "其他错误：" + e.getMessage();
            }
        }else{
            error = "用户名/密码错误";
        }
        return error;
    }

    protected String getHost(ServletRequest request) {
        return IpUtils.getRemoteAddr((HttpServletRequest)request);
    }


    /*
    解密密码
     */
    protected String getPassword(String password){
        // 登录密码解密（解决登录密码明文传输安全问题）
        String secretKey = Global.getProperty("shiro.loginSubmit.secretKey");
        if (StringUtils.isNotBlank(secretKey)){
            password = DesUtils.decode(password, secretKey);
            if (StringUtils.isBlank(password)){
                logger.info("登录密码为空或解码错误.");
            }
        }
        return password;
    }

    /*
    根据账号获取用户
     */
    protected User getOneCodeUser(String account){
        User accountUser = new User();
        accountUser.setPhone(account);
        User user = userExtendService.getByOneCode(accountUser);
        return user;
    }

    /**
     * 获取登录验证码
     */
    protected String getCaptcha(String captcha) {
        // 登录用户名解密（解决登录用户名明文传输安全问题）
        String secretKey = Global.getProperty("shiro.loginSubmit.secretKey");
        //正式环境需加密，默认不需要
        if (StringUtils.isNotBlank(secretKey)){
            captcha = DesUtils.decode(captcha, secretKey);
        }
        return captcha;
    }
}
